import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;

public class SazanaServer
//implements Runnable 
{
	// Datenbank einbinden
	SazanaDatabase database;
	java.util.List<ServerThread> clientList;
	Thread th;
	World world;

	public static void main(String[] args) {
		new SazanaServer();
	}
	
	public boolean login(String benutzername, String passwort, SazanaDatabase MYDB)
	{
		database = MYDB;
        
		try
        {
            Statement statement = database.connection.createStatement();
            ResultSet result = statement.executeQuery("SELECT COUNT(*) AS anzahl FROM users WHERE username = '" + benutzername + "' AND password = '" + passwort + "'");
            result.first();
            int spielerfund = result.getInt("anzahl");
            
            if (spielerfund == 1)
            {
                return true;
            }
        }
        catch (SQLException e)
        {
            System.out.println(e.getMessage());
        }
		
		return false;
	}
	
	public SazanaServer() {
		world=new World(this);
		
		clientList=new java.util.LinkedList<ServerThread>();

		int count=0;
		try {
			System.out.println("Lausche auf Port 3333...");
			ServerSocket echod = new ServerSocket(3333);
			while (true) {
				// Neuen Client erzeugen und in die Liste zufuegen
				Socket socket=echod.accept();
				System.out.print("Incoming transmition...");
				ServerThread client=new ServerThread(++count,socket,this);
				
				// Neuen Spieler anlegen und starten
				Guy guy=world.createGuy();
				client.guy=guy;
				client.start();
				
				// Neuen Spieler an alle Anderen schicken
				for (ServerThread st: clientList) {
					st.out.println("createguy#1");
				}
				// Spieler in die Liste haengen
				clientList.add(client);
				
			}
		}
		catch (IOException e) {
			System.err.println(e.toString());
			System.exit(1);
		}
	}	
	
	
	public void broadCast(String text) {
		for (ServerThread client: clientList) {
			client.sendGuyCmd(text);
		}
	}
	
	public void disconnect(ServerThread client)
	{
		for (ServerThread st: clientList) {
			if (st == client)
			{
				st.guy = null;
				st = null;
			}
		}
		
	}
	
}
